/*This is often the case in practice. Also, assume that
 notifyObservers()'s synchronized statement was not
 present and that its while loop worked with observers directly.
 In that situation, suppose a listener's thread removes the
 listener from the clients data structure, while the for loop is iterating.*/

package conex;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Enumeration;
import java.util.Vector;

/**
 *
 * @author Sandro
 */
public class RemoteObservable implements Remote {
    protected Vector subscribers = new Vector();

  public void addObserver(RemoteObserver s) throws RemoteException {
        System.out.println("Adding 01");
        subscribers.addElement(s);
    }

  public void deleteObserver(RemoteObserver s) throws RemoteException {
    subscribers.removeElement(s);
  }

  public Vector notifyObservers(Object code) throws RemoteException  {
    Vector deadSubs = null;
    Vector<String> names=new Vector<String>();
    Enumeration e = subscribers.elements();
    //System.out.println("Updating 01");
    while (e.hasMoreElements()) {
        RemoteObserver s = (RemoteObserver) e.nextElement();
   //     System.out.println("inside while");
        
        try {
            s.update(code);
      //      System.out.println("Updating 02");
            names.add(s.getUserName());
            
        }
        catch (java.rmi.ConnectException ce) { //serious
            if (deadSubs == null) deadSubs = new Vector();
            deadSubs.addElement(s);// debe estar desconectado
            System.out.println("Desconectado: "+s.toString());
        }
        catch (java.rmi.NoSuchObjectException nsoe){ //serious
            if (deadSubs == null) deadSubs = new Vector();
            deadSubs.addElement(s);// must be dead
            System.out.println("Desconectado: "+s.toString());
        }
        catch (java.rmi.RemoteException re) {
        /*might recover?*/
           if (deadSubs == null) deadSubs = new Vector();
            deadSubs.addElement(s);
            
            System.out.println("might recover?");
        }
    }
    if (deadSubs != null) {
        e = deadSubs.elements();
        while (e.hasMoreElements()) {
            RemoteObserver s = (RemoteObserver) e.nextElement();
            deleteObserver(s);  // Olvidar este RemoteObserver
        }
     }

    return names;
  }


}
